#include "resource_manager.h"

namespace SkyID 
{

//- ResourceManager -----------------------------------------------------------

namespace ResourceManager
{

static t_resource_array gResources;

bool initialize(const Config &config)
{
	gResources.reserve(100);

	LOG_MSG("ResourceManager: initialized");
	return true;
}

void shutdown()
{
	t_resource_iterator i = gResources.begin(), ie = gResources.end();
	while (i != ie)
		delete *i++;
	gResources.clear();

	LOG_MSG("ResourceManager: shutdown");
}

Image* loadImage(const char *fileName)
{
	Reader *reader = VFS::getReader(fileName);
	if (!reader)
		return NULL;
	Image *image = NULL;
	if (CheckExt(fileName, "png"))
		image = new ImagePNG(reader);
	else if (CheckExt(fileName, "jpg"))
		image = new ImageJPEG(reader);
	delete reader;
	if (image)
		gResources.push_back(image);
	return image;
}

Texture* loadTexture(const char *fileName, GLenum mode)
{
	Texture *texture = NULL;
	Image *image = loadImage(fileName);
	if (image && image->isValid())
		texture = new Texture(image, mode);
	//delete image;
	if (texture)
		gResources.push_back(texture);
	return texture;
}

Sound* loadSound(const char *fileName)
{
#ifndef SKYID_DISABLE_SOUND
	Reader *reader = VFS::getReader(fileName);
	if (!reader)
		return NULL;
	Sound *sound = NULL;
	if (CheckExt(fileName, "wav"))
		sound = new SoundWAV(reader);
	else if (CheckExt(fileName, "ogg"))
		sound = new SoundOGG(reader);
	delete reader;
	if (sound)
		gResources.push_back(sound);
	return sound;
#else
	return NULL;
#endif
}

Music* loadMusic(const char *fileName)
{
#ifndef SKYID_DISABLE_SOUND
	Reader *reader = VFS::getReader(fileName);
	if (!reader)
		return NULL;
	Music *music = NULL;
	if (CheckExt(fileName, "ogg"))
		music = new MusicOGG(reader);
	else
		delete reader;
	if (music)
		gResources.push_back(music);
	return music;
#else
	return NULL;
#endif
}

} // ResourceManager

} // namespace SkyID
